// Author:
//   Jason Couture, plaguethenet@gmail.com
//
// Copyright (c) 2007-2011, Jason Couture
//
// All rights reserved.
//
// If you wish to use XML Settings in your application, YOU MUST FIRST request permission.
// This source is provided to the llAma project to ease the build process on linux systems.
// It may be modified and used with llAma only, And not in another project, or released on
// its own, Without my express written permssion. AKA, ALL RIGHTS RESERVED.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace XMLSettings
{
    class HelperFunctions
    {
        private static string ToBase64(byte[] data)
        {
            if (data == null) throw new ArgumentNullException("data");
            return Convert.ToBase64String(data);
        }
        private static byte[] FromBase64(string base64)
        {
            if (base64 == null || base64 == "") throw new ArgumentNullException("base64");
            return Convert.FromBase64String(base64);
        }
        private static byte[] Serialize(object obj)
        {
            MemoryStream objMemStream = new MemoryStream();
            BinaryFormatter objBinaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
            objBinaryFormatter.Serialize(objMemStream, obj);
            objMemStream.Close();
            return objMemStream.ToArray();
        }
        private static object Deserialize(byte[] obj)
        {
            MemoryStream objMemStream = new MemoryStream(obj);
            BinaryFormatter objBinaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
            return objBinaryFormatter.Deserialize(objMemStream);
        }
        public static string SerializeToString(object obj)
        {
            return ToBase64(Serialize(obj));
        }
        public static object DeserializeFromString(string base64)
        {
            return Deserialize(FromBase64(base64));
        }
    }
}
